//
//  ZJMoveOptions.swift
//  MoveOptions
//
//  Created by zhengju on 2017/8/1.
//  Copyright © 2017年 zhengju. All rights reserved.
//

import UIKit

public enum ZJMoveOptionsStyle : Int {
    
    
    case viewLong // collectionView加长按手势
    
    case cellLong // collectionViewCell加长按手势
    
}


class ZJMoveOptions: UIViewController {

    
    var saveAction:((_ array:Array<ZJMoveOptionsModel>)->())?
    
    
    var moveOptions: Array<Array<ZJMoveOptionsModel>>?
    var selectedOptions: Array<ZJMoveOptionsModel>?
    
    var collectionView: UICollectionView?
    var layout: UICollectionViewFlowLayout?
    
    let sectionInsets = UIEdgeInsets(top: 10.0, left: 10.0, bottom: 10.0, right: 10.0)
    
    var style: ZJMoveOptionsStyle?
    
    var width :CGFloat!
    
    let height = UIScreen.init().bounds.size.height
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.title = "移动选项"

        width = self.view.bounds.size.width

        let space :CGFloat = 10

        let cellW = (width - 6*space)/5.0

        layout = UICollectionViewFlowLayout()
        layout?.itemSize = CGSize.init(width: cellW, height: 30)
        //调节行间距
        layout?.minimumLineSpacing = 10
        //调节列间距
        layout?.minimumInteritemSpacing = 10
        
        collectionView = UICollectionView.init(frame: self.view.bounds, collectionViewLayout: layout!)
        
        collectionView?.backgroundColor = UIColor.init(red: 236/255, green: 236/255, blue: 236/255, alpha: 1.0)
        
        collectionView?.delegate = self
        collectionView?.dataSource = self
        collectionView?.register(ZJMoveOptionsCell.self, forCellWithReuseIdentifier: NSStringFromClass(ZJMoveOptionsCell.self))
        collectionView?.register(ZJMoveOptionsHeaderView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: NSStringFromClass(ZJMoveOptionsHeaderView.self))
        self.view.addSubview(collectionView!)

        if style == .viewLong{
         
            let longPressGesture = UILongPressGestureRecognizer();
            longPressGesture.addTarget(self, action: #selector(longPressAction(longPress:)))
            collectionView?.addGestureRecognizer(longPressGesture)

        }

        let saveBtn = UIButton()
        saveBtn.frame = CGRect.init(x: 0, y: 0, width: 60, height: 30)
        saveBtn.addTarget(self, action: #selector(saveClick(button:)), for: .touchUpInside)
        saveBtn.setTitle("保存", for: .normal)
        saveBtn.setTitleColor(UIColor.black, for: .normal)
        self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(customView: saveBtn)
   
    }
    func saveClick(button:UIButton)  {
        
        selectedOptions = moveOptions?.first
        if (selectedOptions?.isEmpty)! {
            
            print("您还没有选中的选项")
            
            return
        }
        
        if saveAction != nil {
            
            saveAction!(selectedOptions!)
            self.navigationController?.popViewController(animated: true)
        }
    }

    func longPressAction(longPress: UILongPressGestureRecognizer)  {
        let point = longPress.location(in: collectionView)
        let indexPath = collectionView?.indexPathForItem(at: point)
        //根据长按手势的状态进行处理
        switch longPress.state {
        case .began:
            //当没有点击到cell的时候不进行处理
            if !(indexPath != nil){
            break
                
            }
            //开发移动
            collectionView?.beginInteractiveMovementForItem(at: indexPath!)
            break
        case .changed:
            //移动过程中更新位置坐标
            collectionView?.updateInteractiveMovementTargetPosition(point)
            break
        case .ended:
            //停止移动调用此方法
            collectionView?.endInteractiveMovement()
            break
        default:
            //取消移动
            collectionView?.cancelInteractiveMovement()
            break
        }
    }
}
extension ZJMoveOptions: UICollectionViewDataSource{
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: NSStringFromClass(ZJMoveOptionsCell.self), for: indexPath) as! ZJMoveOptionsCell
        
        let model = moveOptions?[indexPath.section][indexPath.row]
        
        cell.model = model
        
        cell.longAction = { [weak self] in
        //显示删除按钮
            
            
            
        }
        
        
        
        cell.deleteAction = {[weak self] in
        
            let arr = self?.moveOptions?.last

            self?.reloadCollectionView(sourceIndexPath: indexPath, to: IndexPath.init(row: (arr?.count)!, section: 1))
            
            self?.collectionView?.reloadData()

            
        }
        cell.clickAction = {[weak self] in

           
                let arr = self?.moveOptions?.first

                self?.reloadCollectionView(sourceIndexPath: indexPath, to: IndexPath.init(row: (arr?.count)!, section: 0))
                
                self?.collectionView?.reloadData()
                
            }

        return cell
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        let arr = moveOptions?[section]
        return arr!.count
        
    }
    public func numberOfSections(in collectionView: UICollectionView) -> Int{
  
        return (moveOptions?.count)!
    }
    
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
       
        
        let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: NSStringFromClass(ZJMoveOptionsHeaderView.self), for: indexPath) as!  ZJMoveOptionsHeaderView
        
        if kind == UICollectionElementKindSectionHeader {
            header.title = ["选中的选项","备用的选项"][indexPath.section]
            }
        
        return header
        
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        return CGSize.init(width: width, height: 30)
    }

}
extension ZJMoveOptions: UICollectionViewDelegate{
    // 在开始移动时会调用此代理方法，
    func collectionView(_ collectionView: UICollectionView, canMoveItemAt indexPath: IndexPath) -> Bool {
         //根据indexpath判断单元格是否可以移动，如果都可以移动，直接就返回YES ,不能移动的返回NO
        return true
    }
    //// 在移动结束的时候调用此代理方法
    func collectionView(_ collectionView: UICollectionView, moveItemAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
        
      reloadCollectionView(sourceIndexPath: sourceIndexPath, to: destinationIndexPath)
        
    }
    func reloadCollectionView(sourceIndexPath: IndexPath,to destinationIndexPath: IndexPath)  {
        
        var sourceArray = moveOptions?[sourceIndexPath.section]
        
        let model = sourceArray?[sourceIndexPath.row]
        
        
        if sourceIndexPath.section == 0 {
            model?.isDisplayDelete = false
            model?.isLongPress = false
        }else{
            model?.isDisplayDelete = true
            model?.isLongPress = true
        }
        
        sourceArray?.remove(at: sourceIndexPath.row)
        
        moveOptions?[sourceIndexPath.section] = sourceArray!
        
        var destinationArray: Array<ZJMoveOptionsModel>
        
        
        if destinationIndexPath.section == sourceIndexPath.section {
            
            destinationArray = sourceArray!
            
        }else{
            
            destinationArray = (moveOptions?[destinationIndexPath.section])!
        }
        
        destinationArray.insert(model!, at: destinationIndexPath.row)
        
        moveOptions?[destinationIndexPath.section] = destinationArray
    }
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        let model = moveOptions?[indexPath.section][indexPath.row]
        
        print("点击了" + (model?.title!)!)
        
    }
}
extension ZJMoveOptions: UICollectionViewDelegateFlowLayout{
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return sectionInsets
    }
}
